//
//  BRSApiClient.m
//  Pint
//
//  Created by xiect on 13-10-25.
//  Copyright (c) 2013年 brains. All rights reserved.
//

#import "BRSApiClient.h"
#import "AFXMLRequestOperation.h"


@implementation BRSApiClient

+ (BRSApiClient *)sharedClient {
    static BRSApiClient *_sharedClient = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedClient = [[BRSApiClient alloc] initWithBaseURL:[NSURL URLWithString:kHTTP_URL_AZURE]];
    });
    return _sharedClient;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (!self) {
        return nil;
    }
    
    [self registerHTTPOperationClass:[BRSXMLRequestOperation class]];
    
    // Accept HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
	[self setDefaultHeader:@"Accept" value:@"application/xml"];
    
    // By default, the example ships with SSL pinning enabled for the app.net API pinned against the public key of adn.cer file included with the example. In order to make it easier for developers who are new to AFNetworking, SSL pinning is automatically disabled if the base URL has been changed. This will allow developers to hack around with the example, without getting tripped up by SSL pinning.
    if ([[url scheme] isEqualToString:@"https"]) {
        self.defaultSSLPinningMode = AFSSLPinningModePublicKey;
    } else {
        self.defaultSSLPinningMode = AFSSLPinningModeNone;
    }

    return self;
}

- (NSMutableURLRequest *)requestWithMethod:(NSString *)method path:(NSString *)path parameters:(NSDictionary *)parameters
{
    NSMutableURLRequest *request = [super requestWithMethod:method path:path parameters:parameters];
    NSSet *methodsWithNoBody = [NSSet setWithObjects:@"GET", @"HEAD", @"DELETE", nil];
    
    if (parameters != nil && ![methodsWithNoBody containsObject:method])
    {
        NSString *charset = (__bridge NSString *)CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(self.stringEncoding));
        [self addHTTPBodyToRequest:request withParameters:parameters charset:charset];
    }
    
    return request;
}

- (void)addHTTPBodyToRequest:(NSMutableURLRequest *)request withParameters:(NSDictionary *)parameters charset:(NSString *)charset
{
    switch (self.parameterEncoding)
    {
        case XMLParameterEncoding:  // If it's our custom encoding...
        {
            [request setValue:[NSString stringWithFormat:@"text/xml; charset=%@", charset] forHTTPHeaderField:@"Content-Type"];
             [request addValue: @"http://www.Nanonull.com/TimeService/getOffesetUTCTime" forHTTPHeaderField:@"SOAPAction"];
            
            // Create the request body
//            NSMutableString *body = [NSMutableString string];
            // ** Append your XML request to the body string here **
            NSString * soapMessage = @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
            "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
            "<soap:Body>\n"
            "<getOffesetUTCTime xmlns=\"http://www.Nanonull.com/TimeService/\">\n"
            "<hoursOffset>12</hoursOffset>\n"
            "</getOffesetUTCTime>\n"
            "</soap:Body>\n"
            "</soap:Envelope>\n";
            
            NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
            [request addValue: msgLength forHTTPHeaderField:@"Content-Length"];
            [request setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
            break;
        }
        default:
        {
            break;
        }
    }
    
    // ** Set any additional headers, etc here **
}

#pragma mark-
#pragma mark api method
-(void) loginWithId:(NSString*)userId password:(NSString*) password onSuccess:(ArrayBlock)successBlock{
    NSDictionary* dic = [NSDictionary dictionaryWithObjectsAndKeys:userId,@"user_id",password,@"user_pwd", nil];
    // soap xml
    [self registerHTTPOperationClass:[BRSXMLRequestOperation class]];
    
    [self postPath:@"TimeService.asmx" parameters:dic success:^(AFHTTPRequestOperation *operation, id retDic) {
//        for (NSDictionary *attributes in postsFromResponse) {
//            Post *post = [[Post alloc] initWithAttributes:attributes];
//            [mutablePosts addObject:post];
//        }
        
        if (successBlock) {
            successBlock([NSArray array], nil);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (successBlock) {
            successBlock([NSArray array], error);
        }
    }];

}
@end
